package com.example.lianguisystem.controller;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.lianguisystem.DTO.LianGuiLabelDTO;
import com.example.lianguisystem.VO.LianGuiNoSubmitVO;
import com.example.lianguisystem.VO.ListLabelDataVO;
import com.example.lianguisystem.common.FineReportConstant;
import com.example.lianguisystem.common.Result;
import com.example.lianguisystem.entity.*;
import com.example.lianguisystem.mapper.GzrsLabelMapper;
import com.example.lianguisystem.mapperLianGui.*;
import com.example.lianguisystem.mapperLianGui.statistics.ICombinMapper;
import com.example.lianguisystem.mapperLianGui.statistics.ICombindetailMapper;
import com.example.lianguisystem.service.*;
import com.example.lianguisystem.utils.licensePlate.Base64Util;
import com.example.lianguisystem.utils.licensePlate.CommonUtil;
import com.example.lianguisystem.utils.licensePlate.FileUtil;
import com.example.lianguisystem.utils.licensePlate.HttpUtil;
import com.google.common.net.MediaType;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/lianGuiLabel")
@Api(tags = "莲桂标签打印")
@CrossOrigin
@Slf4j
public class LianGuiLabelController {

    private String savePath = "D:\\Supplier\\UploadFiles\\cdq-dev-storage\\lianGuiPersonInfo\\";
//    private String savePath = "\\\\192.168.0.192\\UploadFiles\\cdq-dev-storage\\lianGuiPersonInfo\\";
    private String httpPath = "http://116.6.92.6:8076/liangui/d/lianGuiPersonInfo/";

    @Autowired
    private LabelStatusMapper labelStatusMapper;

    @Autowired
    private IDrawMapper iDrawMapper;
    @Autowired
    private IDrawdetailMapper iDrawdetailMapper;

     Logger logger = LoggerFactory.getLogger(LianGuiLabelController.class);


    @Autowired
    private MaterialRequisitionService materialRequisitionService;
    @Autowired
    private DailyCapacityMapper dailyCapacityMapper;

    final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    private static final ConcurrentHashMap<String, Object> keyLocks = new ConcurrentHashMap<>();

    @Autowired
    private LabelMapper labelMapper;

    @Autowired
    private SalesOrderMapper salesOrderMapper;

    @Autowired
    private LianGuiIdCardRecordMapper idCardRecordMapper;


    @Autowired
    private GzrsLabelMapper gzrsLabelMapper;

    String[] fenQieArr = new String[]{"1925755778764468225", "1925755778764468226"};

    @Autowired
    private LianGuiLabelService lianGuiLabelService;


    @Autowired
    private CommonService commonService;


    @Autowired
    private ICombinMapper iCombinMapper;
    @Autowired
    private ICombindetailMapper iCombindetailMapper;


    @Autowired
    private CommonSettingService commonSettingService;
    @Autowired
    private CommonMapper commonMapper;


    @Autowired
    private DailyCapacityService dailyCapacityService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private String versionKey = "version190App";

    @GetMapping("/test1")
    public void test1( String ycno) {
        System.out.println(ycno);
    }

    @ApiOperation(value = "销货清单-扫描任意一张标签获取销货重打数据", notes = "销货清单-扫描任意一张标签获取销货重打数据")
    @GetMapping("/queryPrintAgainData")
    public Result queryPrintAgainData(@RequestParam("label") String label) {
        Integer billid = labelMapper.selectBillByLabel(label);
        if (billid == null) {
            return Result.fail("标签未生成送货单");
        }
        List<LianGuiLabelRecord> lianGuiLabelRecords = labelMapper.selectCollectData(billid);
        LianGuiNoSubmitVO lianGuiNoSubmitVO = new LianGuiNoSubmitVO();
        lianGuiNoSubmitVO.setList(lianGuiLabelRecords);
        lianGuiNoSubmitVO.setTitle(lianGuiLabelRecords.get(0).getClient() + "   " + lianGuiLabelRecords.get(0).getPlate());
        lianGuiNoSubmitVO.setBillId(billid);
        return Result.success(lianGuiNoSubmitVO);
    }

    @ApiOperation(value = "销货清单-销货单重打", notes = "销货清单-销货单重打")
    @GetMapping("/printAgain")
    public Result printAgain(@RequestParam("billId") Integer billId, @RequestParam("type") String type, @RequestParam("printer") String printer) {
        if ("print".equals(type)) {
            try {
                printer = URLEncoder.encode(printer, "UTF-8").replace("+", "%20");
                //调用url，相当于浏览器携带参数直接打开网址
                String url = FineReportConstant.FINE_REPORT_URI + "DQ/LianGuiXiaoHuoDetail.cpt^&billid=" + billId + "^&dyj=" + printer;
                Runtime.getRuntime().exec("cmd /c start  " + url);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return Result.success();
        }
        String url = FineReportConstant.FINE_REPORT_URI + "DQ/LianGuiXiaoHuoDetail.cpt&billid=" + billId + "&format=pdf";
        String filePath = savePath + "preViewPdf\\";
        String fileName = billId + "preViewPdf.pdf";
        CommonUtil.FRDownload(url, filePath, fileName);
        return Result.success(httpPath + "preViewPdf/" + fileName);
    }


    @ApiOperation(value = "标签打印-查询品号信息", notes = "标签打印-查询品号信息")
    @GetMapping("/queryByCpTypeNo")
    public Result queryByCpTypeNo(@RequestParam(value = "currentPage", required = false) Integer currentPage, @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                  @RequestParam(value = "cpTypeNo", required = false) String cpTypeNo) {
        List<LianGuiLabelRecord> mapList = labelMapper.listByProdName(currentPage, pageSize, cpTypeNo);
        Integer count = mapList.size();
        return Result.success(mapList, count);
    }

    @PostMapping("/queryWeightByMachine")
    public Result queryWeightByMachine(@RequestBody LianGuiLabelRecord lianGuiLabelRecord) {

        String machine = lianGuiLabelRecord.getMachine();
        String id = "";
        if (machine.contains("分切") && (machine.contains("3") || machine.contains("4"))) {
            id = fenQieArr[0];
        }
        if (machine.contains("分切") && (machine.contains("1") || machine.contains("2"))) {
            id = fenQieArr[1];
        }

        Map<String, Object> currentWeight = labelMapper.selectCurrentWeight(id);
        if (currentWeight == null) {
            return Result.success("");
        }
        String recordDateStr = (String) currentWeight.get("recordDate");
        lianGuiLabelRecord.setWeight(((BigDecimal) currentWeight.get("weight")).doubleValue());

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime recordDate = LocalDateTime.parse(recordDateStr, dtf);
        LocalDateTime now = LocalDateTime.now().minusMinutes(5);
        if (recordDate.isAfter(now) && lianGuiLabelRecord.getCpTypeNo().contains("分切")) {
            return Result.success(((BigDecimal) currentWeight.get("weight")).doubleValue() + "");
        }
        return Result.success("");
    }

    @ApiOperation(value = "标签打印第二版-扫描生产通知单获取信息")
    @GetMapping("/queryBySoBillcode")
    public Result queryBySoBillcode(@RequestParam("soBillcode") String soBillcode, @RequestParam("username") String username) {
        Boolean overweight = labelMapper.isOverweight(soBillcode);
        if (overweight) {
            return Result.fail("生产通知单扫码重量已达到订单重量的150%");
        }
        LianGuiLabelRecord lianGuiLabelRecord = labelMapper.selectLabelDataBySoBillCode(soBillcode);
        if (lianGuiLabelRecord == null) {
            return Result.fail("标签空数据");
        }
        LianGuiLabelRecord temp = labelMapper.selectPreLabelData(username);
        if (temp != null) {

            lianGuiLabelRecord.setMachine(temp.getMachine());
            lianGuiLabelRecord.setPieceUps("");
        }
        String machine = lianGuiLabelRecord.getMachine() != null ? lianGuiLabelRecord.getMachine() : "";
        String id = "";
        if (machine.contains("分切") && (machine.contains("3") || machine.contains("4"))) {
            id = fenQieArr[0];
        }
        if (machine.contains("分切") && (machine.contains("1") || machine.contains("2"))) {
            id = fenQieArr[1];
        }

        String workshop = labelMapper.selectWorkshop(soBillcode);

        String str = stringRedisTemplate.opsForValue().get("salesOrder:machine");
        List<String> list = JSON.parseObject(str, List.class);
        List<String> collect = list.stream().filter(item -> item.contains(workshop)).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("machineArr", collect);
        map.put("record", lianGuiLabelRecord);
        Map<String, Object> currentWeight = labelMapper.selectCurrentWeight(id);
        if (currentWeight == null) {
            return Result.success(map);
        }
        String recordDateStr = (String) currentWeight.get("recordDate");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime recordDate = LocalDateTime.parse(recordDateStr, dtf);
        LocalDateTime now = LocalDateTime.now().minusMinutes(5);
        if (recordDate.isAfter(now)) {
            lianGuiLabelRecord.setWeight(((BigDecimal) currentWeight.get("weight")).doubleValue());
        }
        return Result.success(map);
    }

    @ApiOperation(value = "销货清单-获取下拉框选项", notes = "销货清单-获取下拉框选项")
    @GetMapping("/querySelection")
    public Result querySelection() {
        List<Map<String, Object>> listOfClient = labelMapper.listOfClient();
        List<Map<String, String>> listOfWarehouse = labelMapper.listOfWarehouse();
        List<LianGuiIdCardRecord> lianGuiIdCardRecords = labelMapper.listHasIdCard();
        List<Map<String, String>> soBillCodeOfSelection = labelMapper.listSoBillCodeOfSelection();
        List<Object> resList = new ArrayList<>();
        resList.add(listOfClient);
        resList.add(listOfWarehouse);
        resList.add(lianGuiIdCardRecords);
        resList.add(soBillCodeOfSelection);
        return Result.success(resList);
    }


    @ApiOperation(value = "标签打印-获取分切机列表", notes = "标签打印-获取分切机列表")
    @GetMapping("/queryMachineSelection")
    public Result queryMachineSelection() {

        String str = stringRedisTemplate.opsForValue().get("salesOrder:machine");
        List<String> list = JSON.parseObject(str, List.class);
//        List<String> list = commonMapper.listOfWorkshopOsString(username);
//        if (list.size() <= 0) {
//            commonMapper.listOfWorkshopOsString(null);
//        }
        return Result.success(list);
    }

    @ApiOperation(value = "销货清单-查询打印机列表", notes = "销货清单-查询打印机列表")
    @GetMapping("/queryPrinter")
    public Result queryPrinter(@RequestParam("username") String username) {
        List<String> list = gzrsLabelMapper.selectPrinter();
        CommonSetting commonSetting = commonSettingService.getCommonSetting(username, "莲桂标签打印");
        List<Object> resList = new ArrayList<>();
        resList.add(list);
        resList.add(commonSetting);
        return Result.success(resList);
    }

    @ApiOperation(value = "标签打印-查询是否disabled", notes = "是否disabled-查询是否disabled")
    @GetMapping("/queryDisabled")
    public Result queryDisabled() {
        String disable = stringRedisTemplate.opsForValue().get("salesOrder:disable");
        return Result.success(disable);
    }

    @ApiOperation(value = "标签打印-设置是否disabled", notes = "标签打印-设置是否disabled")
    @GetMapping("/setDisabled")
    public Result setDisabled(@RequestParam("disable") String disable) {
        stringRedisTemplate.opsForValue().set("salesOrder:disable", disable);
        return Result.success();
    }


    @ApiOperation(value = "销货清单-保存打印机配置", notes = "销货清单-保存打印机配置")
    @PostMapping("/saveCommonSetting")
    public Result saveCommonSetting(@RequestBody CommonSetting commonSetting) {
        commonSettingService.addOrEditCommonSetting(commonSetting);
        return Result.success();
    }


    @ApiOperation(value = "销货清单-登录", notes = "销货清单-登录")
    @GetMapping("/login")
    public Result login(@RequestParam("account") String account, @RequestParam("password") String password) {
        String username = labelMapper.selectIsHasAccount(account);
        if (StrUtil.isBlank(username)) {
            return Result.fail("用户名不存在");
        }
        Map<String, String> map = labelMapper.selectLoginUsername(account, password);
        if (map == null) {
            return Result.fail("密码错误");
        }
        return Result.success(map);
    }

    @GetMapping("/removeUpdateBy")
    public Result removeUpdateBy(@RequestParam("id") String labelId) {
        Integer integer = labelMapper.updateUpdateBy(labelId);
        LianGuiLabelStatus lianGuiLabelStatus = new LianGuiLabelStatus();
        lianGuiLabelStatus.setLabelId(labelId);
        lianGuiLabelStatus.setStatus((byte) 2);
        labelStatusMapper.deleteStatus(lianGuiLabelStatus);
        if (integer == 0) {
            return Result.fail("标签已生成送货单，不允许删除");
        }
        return Result.success();
    }


    @ApiOperation(value = "销货清单-扫描标签", notes = "销货清单-扫描标签")
    @GetMapping("/queryByLabel")
    @Transactional(rollbackFor = Exception.class, transactionManager = "lianGuiTransactionManager")
    public Result queryByLabel(@RequestParam("label") String label, @RequestParam("username") String username,
                               @RequestParam("client") String client, @RequestParam("plate") String plate, @RequestParam(value = "salesOrderId", required = false) String salesOrderId) {
        Integer integer = labelMapper.selectLabelStatus(label, 1);
        if (integer > 0) {
            return Result.fail("标签已销货");
        }
        LianGuiLabelRecord lianGuiLabelRecord = labelMapper.selectByLabel(label);
        if (lianGuiLabelRecord == null) {
            return Result.fail("标签不存在");
        }
        integer = labelMapper.selectLabelStatus(label, 2);
        if (StrUtil.isNotBlank(lianGuiLabelRecord.getUpdateBy()) && lianGuiLabelRecord.getUpdateDate() != null && integer > 0) {
            Date updateDate = lianGuiLabelRecord.getUpdateDate();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy年M月d日 H点m分");
            String format = simpleDateFormat.format(updateDate);
            return Result.fail("标签已被" + lianGuiLabelRecord.getUpdateBy() + "于" + format + "扫描，车牌(" + lianGuiLabelRecord.getPlate() + ")，客户(" + lianGuiLabelRecord.getClient() + ")，请联系并删除");
        }
        String newLabelId = labelMapper.selectIsHasNewLabelId(label);
        if (StrUtil.isNotBlank(newLabelId)) {
            return Result.fail("标签已进行以旧换新，请扫描新标签：" + newLabelId);
        }
        String tempOrderId = null;
        if (StrUtil.isNotBlank(salesOrderId)) {
            String[] split = salesOrderId.split(",");
            String[] result = Arrays.stream(split)
                    .filter(Objects::nonNull)  // 移除null
                    .filter(s -> StrUtil.isNotBlank(s)) // 移除空字符串
                    .toArray(String[]::new);
            Boolean flag = true;
            for (String tempId : result) {
                SalesOrder salesOrder = salesOrderMapper.selectSalesOrderByBillCode(tempId);
                if (salesOrder.getSpecification().equals(lianGuiLabelRecord.getExtent())
                        && salesOrder.getPilesNum().equals(lianGuiLabelRecord.getPilesNum())
                        && salesOrder.getRation().equals(lianGuiLabelRecord.getRation())
                ) {
                    if (StrUtil.isNotBlank(lianGuiLabelRecord.getBillcode())) {
                        flag = false;
                        break;
                    }
                    if (StrUtil.isBlank(lianGuiLabelRecord.getBillcode()) && salesOrder.getDesignNo().equals(lianGuiLabelRecord.getDesignNo())) {
                        tempOrderId = salesOrderMapper.selectIdByBillid(salesOrder.getOrderBillid());
                        flag = false;
                        break;
                    }
                }
            }

            if (StrUtil.isBlank(lianGuiLabelRecord.getBillcode()) && StrUtil.isBlank(tempOrderId)) {
                return Result.fail("标签品号和订单品号不匹配，请选择匹配订单");
            }
            if (flag) {
                return Result.fail("标签幅宽,层数,定量与订单不一致");
            }
        }
        String[] split = client.split("-");
        lianGuiLabelRecord.setClient(split[0]);
        lianGuiLabelRecord.setPlate(plate);
        lianGuiLabelRecord.setStatus((byte) 2);
        lianGuiLabelRecord.setUpdateBy(username);
        lianGuiLabelRecord.setUpdateDate(new Date());
        if (StrUtil.isNotBlank(tempOrderId)) {
            lianGuiLabelRecord.setSalesOrderId(tempOrderId);
        }
        labelMapper.updateById(lianGuiLabelRecord);
        LianGuiLabelStatus lianGuiLabelStatus = new LianGuiLabelStatus();
        lianGuiLabelStatus.setLabelId(lianGuiLabelRecord.getId());
        lianGuiLabelStatus.setStatus(lianGuiLabelRecord.getStatus());
        lianGuiLabelStatus.setRecordDate(new Date());
        lianGuiLabelStatus.setRecordBy(lianGuiLabelRecord.getUpdateBy());
        labelStatusMapper.insertIntoLabelStatus(lianGuiLabelStatus);
//        int i = 1 / 0;
        return Result.success(lianGuiLabelRecord);
    }

    @ApiOperation(value = "销货清单-查询已扫描未提交标签", notes = "销货清单-查询已扫描未提交标签")
    @GetMapping("/listLabelData")
    public Result listLabelData(ListLabelDataVO listLabelDataVO) {
        List<LianGuiLabelRecord> lianGuiLabelRecords = labelMapper.selectLabelData(listLabelDataVO);
        Map<String, List<LianGuiLabelRecord>> resMap = new LinkedHashMap<>();
        for (LianGuiLabelRecord lianGuiLabelRecord : lianGuiLabelRecords) {
            String title = lianGuiLabelRecord.getName() + "  " + lianGuiLabelRecord.getOfficialPlate();
            if (resMap.containsKey(title)) {
                List<LianGuiLabelRecord> tempList = resMap.get(title);
                tempList.add(lianGuiLabelRecord);
                continue;
            }
            List<LianGuiLabelRecord> tempList = new ArrayList<>();
            tempList.add(lianGuiLabelRecord);
            resMap.put(title, tempList);
        }

        List<LianGuiNoSubmitVO> voList = new ArrayList<>();
        for (Map.Entry<String, List<LianGuiLabelRecord>> entry : resMap.entrySet()) {
            List<LianGuiLabelRecord> list = entry.getValue();
            Double weight = 0.0;
            Integer caseCount = list.size();
            for (LianGuiLabelRecord lianGuiLabelRecord : list) {
                weight += lianGuiLabelRecord.getWeight();
                lianGuiLabelRecord.setPlate(lianGuiLabelRecord.getOfficialPlate());
            }
            LianGuiNoSubmitVO vo = new LianGuiNoSubmitVO();
            vo.setCaseCount(caseCount);
            vo.setWeight(weight);
            vo.setTitle(entry.getKey());
            vo.setList(list);
            vo.setSubTitle(weight.intValue() + "kg      " + caseCount + "件");
            voList.add(vo);
        }
        return Result.success(voList);
    }

    @ApiOperation(value = "销货清单-上传身份证，驾驶证，行驶证，签名", notes = "销货清单-上传身份证，驾驶证，行驶证，签名")
    @PostMapping("/uploadFile")
    public Result uploadFile(MultipartFile file, LianGuiIdCardRecord lianGuiIdCardRecord) throws IOException {
        String type = lianGuiIdCardRecord.getType();
        String[] split = file.getOriginalFilename().split("\\.");
        String fileName = Long.toHexString(System.currentTimeMillis()) + type + "." + split[split.length - 1];
        File saveFile = new File(savePath + fileName);
        file.transferTo(saveFile);
        String resUrl = httpPath + fileName;
        Map<String, String> map = new HashMap<>();
        if ("身份证".equals(type)) {
            lianGuiIdCardRecord.setIdentityCardUrl(resUrl);
            idcard(savePath + fileName, lianGuiIdCardRecord);
        } else if ("行驶证".equals(type)) {
            lianGuiIdCardRecord.setRegistrationLicenseUrl(resUrl);
            String plate = vehicleLicense(savePath + fileName);
            if (StrUtil.isNotBlank(plate)) {
                lianGuiIdCardRecord.setPlate(plate);
            }
        } else if ("驾驶证".equals(type)) {
            lianGuiIdCardRecord.setDrivingLicenseUrl(resUrl);
        } else if ("签名".equals(type)) {
            lianGuiIdCardRecord.setSignatureUrl(resUrl);
        }
        return Result.success(lianGuiIdCardRecord);
    }

    public String drivingLicense(String path) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/driving_license";
        try {
            // 本地文件路径
            String filePath = path;
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAccessToken();

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String vehicleLicense(String path) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license";
        try {
            // 本地文件路径
            String filePath = path;
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAccessToken();

            String result = HttpUtil.post(url, accessToken, param);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject words_result = jsonObject.getJSONObject("words_result");
            String plate = words_result.getJSONObject("号牌号码").getString("words");
            System.out.println(result);
            return plate;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public String idcard(String path, LianGuiIdCardRecord lianGuiIdCardRecord) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        try {
            // 本地文件路径
            String filePath = path;
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "id_card_side=" + "front" + "&image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAccessToken();

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject words_result = jsonObject.getJSONObject("words_result");
            JSONObject temp = words_result.getJSONObject("姓名");
            String username = temp.getString("words");
            String idCard = words_result.getJSONObject("公民身份号码").getString("words");
            if (StrUtil.isNotBlank(username)) {
                lianGuiIdCardRecord.setDriverName(username);
            }
            if (StrUtil.isNotBlank(idCard)) {
                lianGuiIdCardRecord.setDriverIdCard(idCard);
            }
            return username;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getAccessToken() throws IOException {
        String key = "jeecg:license:plate";
        String accessToken = stringRedisTemplate.opsForValue().get(key);
        if (accessToken != null) {
            return accessToken;
        }
        MediaType mediaType = MediaType.parse("application/json");
        String clientId = "zTVHwkDOXU68ioGxdXrCANVP";
        String clientSecret = "YH8jmGbNqdbQi0n4eYF5OGGG1SE48gtI";
//        String clientId = "AZBs51CAeVWWHmVFXaN25Fl6";
//        String clientSecret = "5iSIqEBQ3pkMkzdxu2aqEqUtKVGC3UQT";
        Request request = new Request.Builder().url("https://aip.baidubce.com/oauth/2.0/token?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=client_credentials").method("GET", null).addHeader("Content-Type", "application/json").addHeader("Accept", "application/json").build();

        Response response = HTTP_CLIENT.newCall(request).execute();
//        System.out.println(response.body().string());
        String body = response.body().string();
        JSONObject jsonObject = JSONObject.parseObject(body);
        accessToken = (String) jsonObject.get("access_token");
        Integer expiresIn = jsonObject.getInteger("expires_in");
        stringRedisTemplate.opsForValue().set(key, accessToken, expiresIn, TimeUnit.SECONDS);
        return accessToken;
    }

    @ApiOperation(value = "标签打印-获取上一个扫码的标签", notes = "标签打印-获取上一个扫码的标签")
    @GetMapping("/queryPreLabelData")
    public Result queryPreLabelData(@RequestParam("username") String username) {
        LianGuiLabelRecord lianGuiLabelRecord = labelMapper.selectPreLabelData(username);
        return Result.success(lianGuiLabelRecord);
    }

    @ApiOperation(value = "标签修改-根据标签获取数据", notes = "标签修改-根据标签获取数据")
    @GetMapping("/queryChangeLabel")
    public Result queryChangeLabel(@RequestParam("label") String label) {

        LianGuiLabelRecord lianGuiLabelRecord = labelMapper.selectChangeLabelData(label);
        if (lianGuiLabelRecord == null) {
            return Result.fail("标签不存在");
        }
        String machine = lianGuiLabelRecord.getMachine() != null ? lianGuiLabelRecord.getMachine() : "";
        String id = "";
        if (machine.contains("分切") && (machine.contains("3") || machine.contains("4"))) {
            id = fenQieArr[0];
        }
        if (machine.contains("分切") && (machine.contains("1") || machine.contains("2"))) {
            id = fenQieArr[1];
        }
//        Map<String, Object> currentWeight = labelMapper.selectCurrentWeight(id);
        Map<String, Object> currentWeight = null;
        String str = stringRedisTemplate.opsForValue().get("salesOrder:machine");

        List<String> list = JSON.parseObject(str, List.class);
        Map<String, Object> map = new HashMap<>();
        map.put("machineArr", list);
        map.put("record", lianGuiLabelRecord);
        if (currentWeight == null) {
            return Result.success(map);
        }
        String recordDateStr = (String) currentWeight.get("recordDate");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime recordDate = LocalDateTime.parse(recordDateStr, dtf);
        LocalDateTime now = LocalDateTime.now().minusMinutes(5);
        if (recordDate.isAfter(now)) {
            lianGuiLabelRecord.setWeight(((BigDecimal) currentWeight.get("weight")).doubleValue());
        }
        return Result.success(map);
    }


    @ApiOperation(value = "旧标签改新标签-根据标签获取数据，有符合的品号，则换成对应品号", notes = "旧标签改新标签-根据标签获取数据，有符合的品号，则换成对应品号")
    @GetMapping("/queryChangeLabelOfOld")
    public Result queryChangeLabelOfOld(@RequestParam("label") String label) {

        LianGuiLabelRecord lianGuiLabelRecord = labelMapper.selectChangeLabelData(label);
        if (lianGuiLabelRecord == null) {
            return Result.fail("标签不存在");
        }

        List<Map<String, Object>> goodsMapList = salesOrderMapper.listOfGoodsSelection(null);
        List<LianGuiLabelRecord> labelRecordList = new ArrayList<>();
        for (Map<String, Object> goodsMap : goodsMapList) {
            String tempCpTypeNo = (String) goodsMap.get("cpTypeNo");
            String[] result = Arrays.stream(tempCpTypeNo.split("\\s+"))  // 按空格分割
                    .filter(s -> !s.isEmpty())                  // 过滤空字符串
                    .toArray(String[]::new);
            LianGuiLabelRecord tempLabel = new LianGuiLabelRecord();
            tempLabel.setCpTypeNo(tempCpTypeNo);
            tempLabel.setDesignNo((String) goodsMap.get("designNo"));
            if (tempCpTypeNo.contains("分切")) {
                if (result.length > 2) {
                    tempLabel.setExtent(result[2]);
                } else {
                    tempLabel.setExtent("");
                }
                if (result.length > 3) {
                    tempLabel.setPilesNum(result[3].replace("层", ""));
                } else {
                    tempLabel.setPilesNum("");
                }
                if (result.length > 4) {
                    tempLabel.setRation(result[4].replace("克", ""));
                } else {
                    tempLabel.setRation("");
                }
            } else {
                tempLabel.setPilesNum("1");
                if (result.length > 2) {
                    tempLabel.setExtent(result[2]);
                } else {
                    tempLabel.setExtent("");
                }
                if (result.length > 3) {
                    tempLabel.setRation(result[3].replace("克", ""));
                } else {
                    tempLabel.setRation("");
                }
            }
//            if (tempCpTypeNo.contains("分切")) {
//                tempLabel.setPilesNum(result[3].replace("层", ""));
//                tempLabel.setExtent(result[2]);
//                tempLabel.setRation(result[4].replace("克", ""));
//            } else {
//                tempLabel.setPilesNum("1");
//                tempLabel.setExtent(result[2]);
//                tempLabel.setRation(result[3].replace("克", ""));
//            }
            labelRecordList.add(tempLabel);
        }
        List<LianGuiLabelRecord> collect = labelRecordList.stream().filter(item -> item.getPilesNum().equals(lianGuiLabelRecord.getPilesNum())
                && item.getExtent().equals(lianGuiLabelRecord.getExtent()) && item.getRation().equals(lianGuiLabelRecord.getRation())
        ).collect(Collectors.toList());
        String str = stringRedisTemplate.opsForValue().get("salesOrder:machine");


        List<String> list = JSON.parseObject(str, List.class);
        Map<String, Object> map = new HashMap<>();
        map.put("machineArr", list);
        map.put("record", lianGuiLabelRecord);
        map.put("collect", new ArrayList<>());
        if (collect.size() == 1) {
            lianGuiLabelRecord.setDesignNo(collect.get(0).getDesignNo());
            lianGuiLabelRecord.setCpTypeNo(collect.get(0).getCpTypeNo());
            return Result.success(map);
        }
        List<LianGuiLabelRecord> resList = new ArrayList<>();
        Gson gson = new Gson();
        for (LianGuiLabelRecord guiLabelRecord : collect) {
            LianGuiLabelRecord temp = gson.fromJson(gson.toJson(lianGuiLabelRecord), LianGuiLabelRecord.class);
            temp.setDesignNo(guiLabelRecord.getDesignNo());
            temp.setCpTypeNo(guiLabelRecord.getCpTypeNo());
            resList.add(temp);
        }
        map.put("collect", resList);
        return Result.success(map);
    }

    @PostMapping("/submit")
    @Transactional(rollbackFor = Exception.class, transactionManager = "lianGuiTransactionManager")
    @ApiOperation(value = "销货清单-提交", notes = "销货清单-提交")
    public synchronized Result submit(@RequestBody LianGuiLabelDTO lianGuiLabelDTO, @RequestParam("printer") String printer) {

        Date saleOrderDate = new Date();

        List<LianGuiLabelRecord> lianGuiLabelRecordList = lianGuiLabelDTO.getLianGuiLabelRecordList();
        LianGuiIdCardRecord lianGuiIdCardRecord = lianGuiLabelDTO.getLianGuiIdCardRecord();
        if (lianGuiLabelRecordList.size() <= 0) {
            return Result.fail("请扫描数据");
        }
        if (StrUtil.isBlank(lianGuiLabelRecordList.get(0).getUpdateBy())) {
            return Result.fail("没有该员工");
        }
        String yuanGongBianHao = labelMapper.selectYuanGongBianHao(lianGuiLabelRecordList.get(0).getUpdateBy());
        if (StrUtil.isBlank(yuanGongBianHao)) {
            return Result.fail("没有该员工");
        }
        List<String> labelList = new ArrayList<>();
        for (LianGuiLabelRecord lianGuiLabelRecord : lianGuiLabelRecordList) {
            labelList.add(lianGuiLabelRecord.getLabel());
        }
        Boolean isSubmit = labelMapper.selectIsSubmit(labelList);
        if (isSubmit) {
            return Result.fail("部分标签已被他人提交，请重新扫码");
        }

        Set<String> set = labelMapper.selectIsExist(labelList);
        if (set.size() < labelList.size()) {
            String errMsg = "标签";
            for (String label : labelList) {
                if (!set.contains(label)) {
                    errMsg += label + ",";
                }
            }
            errMsg += "已更改重量，请扫码最新标签";
            return Result.fail(errMsg);
        }

        String pre = "SS-";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-");
        DateTimeFormatter tempDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = LocalDate.now().format(tempDtf);
        pre = pre + LocalDate.now().format(dtf);
        Integer maxSeq = labelMapper.selectMaxSeq(pre);
        String invoiceNumber = pre + "00001";
        if (maxSeq != null) {
            invoiceNumber = pre + String.format("%05d", maxSeq + 1);
        }
        String maxSellOrderNo = invoiceNumber;
        String idCardId = lianGuiIdCardRecord.getSellOrderId();
        if (StrUtil.isBlank(lianGuiIdCardRecord.getSellOrderId())) {
            idCardId = UUID.randomUUID().toString().replace("-", "");
            lianGuiIdCardRecord.setSellOrderId(idCardId);
            idCardRecordMapper.insertInto(lianGuiIdCardRecord, "打印");
        } else {
            idCardRecordMapper.updateBySellOrderId(lianGuiIdCardRecord);
        }
        for (LianGuiLabelRecord lianGuiLabelRecord : lianGuiLabelRecordList) {
            lianGuiLabelRecord.setClient(lianGuiLabelRecord.getClient().split("-")[0]);
            lianGuiLabelRecord.setSellOrderId(maxSellOrderNo);
            lianGuiLabelRecord.setIdCardId(idCardId);
        }


        // 默认原纸仓
        Map<String, Object> warehouseMap = labelMapper.selectWarehouse("0001");
        Map<String, Object> clientMap = labelMapper.selectClient(lianGuiLabelRecordList.get(0).getClient());
        Integer maxKey = labelMapper.selectMaxSaleKey();

        String serialNum = labelMapper.selectMaxSerialNum();

        for (LianGuiLabelRecord lianGuiLabelRecord : lianGuiLabelRecordList) {
            lianGuiLabelRecord.setStatus((byte) 1);
            lianGuiLabelRecord.setSsaleBillid(maxKey);
            lianGuiLabelRecord.setSerialNum(serialNum);
            lianGuiLabelRecord.setSaleOrderDate(saleOrderDate);

            LianGuiLabelStatus lianGuiLabelStatus = new LianGuiLabelStatus();
            lianGuiLabelStatus.setLabelId(lianGuiLabelRecord.getId());
            lianGuiLabelStatus.setStatus(lianGuiLabelRecord.getStatus());
            lianGuiLabelStatus.setRecordDate(new Date());
            lianGuiLabelStatus.setRecordBy(lianGuiLabelRecord.getUpdateBy());
            labelStatusMapper.insertIntoLabelStatus(lianGuiLabelStatus);
        }

        lianGuiLabelService.updateBatchById(lianGuiLabelRecordList);

        List<String> idList = lianGuiLabelRecordList.stream().map(LianGuiLabelRecord::getId).collect(Collectors.toList());
        List<Map<String, Object>> detailDataList = labelMapper.selectDetailData(idList);
        SSale sSale = getSSale(maxKey, invoiceNumber, clientMap, lianGuiLabelRecordList.get(0), lianGuiIdCardRecord);
        List<SSaledetail> sSaledetailList = new ArrayList<>();
        Double amount = 0.0;
        int itemNo = 2;

        List<LianGuiLabelRecord> newUpdateRecordList = new ArrayList<>();
        for (Map<String, Object> mapData : detailDataList) {
            SSaledetail sSaledetail = getSSaledetail(maxKey, mapData, warehouseMap, clientMap, itemNo);
            sSaledetailList.add(sSaledetail);
            amount += sSaledetail.getAmount();
            String idStr = (String) mapData.get("idStr");
            List<String> collect = Arrays.stream(idStr.split(",")).filter(s -> StrUtil.isNotBlank(s)).collect(Collectors.toList());
            for (String tempId : collect) {
                LianGuiLabelRecord temp = new LianGuiLabelRecord();
                temp.setId(tempId);
                temp.setItemNo(itemNo);
                temp.setStatus((byte) 1);
                newUpdateRecordList.add(temp);
            }
            itemNo++;
        }
        sSale.setAmount(amount);
        sSale.setLcamount(amount);
        SSalechild sSalechild = getSSalechild(maxKey, amount);
        lianGuiLabelService.insertIntoSSale(sSale);
        for (SSaledetail sSaledetail : sSaledetailList) {
            lianGuiLabelService.insertIntoSSaledetail(sSaledetail);
        }
        lianGuiLabelService.insertIntoSSalechild(sSalechild);


        lianGuiLabelService.updateBatchById(newUpdateRecordList);
        labelMapper.execup_ab_billprint_insert(maxKey, invoiceNumber, format, sSale.getOpid(), sSale.getShopid());
//        int i = 1 / 0;
        try {
            printer = URLEncoder.encode(printer, "UTF-8").replace("+", "%20");
            //调用url，相当于浏览器携带参数直接打开网址
            String url = FineReportConstant.FINE_REPORT_URI + "DQ/LianGuiXiaoHuoDetail.cpt^&billid=" + maxKey + "^&dyj=" + printer;
            Runtime.getRuntime().exec("cmd /c start  " + url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success();
    }


    @PostMapping("/preview")
    @ApiOperation(value = "销货清单-预览", notes = "销货清单-预览")
    public Result preview(@RequestBody LianGuiLabelDTO lianGuiLabelDTO, @RequestParam("printer") String printer) {

        List<LianGuiLabelRecord> lianGuiLabelRecordList = lianGuiLabelDTO.getLianGuiLabelRecordList();
        LianGuiIdCardRecord lianGuiIdCardRecord = lianGuiLabelDTO.getLianGuiIdCardRecord();
        if (lianGuiLabelRecordList.size() <= 0) {
            return Result.fail("请扫描数据");
        }
        if (StrUtil.isBlank(lianGuiLabelRecordList.get(0).getUpdateBy())) {
            return Result.fail("没有该员工");
        }
        String yuanGongBianHao = labelMapper.selectYuanGongBianHao(lianGuiLabelRecordList.get(0).getUpdateBy());
        if (StrUtil.isBlank(yuanGongBianHao)) {
            return Result.fail("没有该员工");
        }
        List<String> labelList = new ArrayList<>();
        for (LianGuiLabelRecord lianGuiLabelRecord : lianGuiLabelRecordList) {
            labelList.add(lianGuiLabelRecord.getLabel());
        }
        Boolean isSubmit = labelMapper.selectIsSubmit(labelList);
        if (isSubmit) {
            return Result.fail("部分标签已被他人提交，请重新扫码");
        }
        Set<String> set = labelMapper.selectIsExist(labelList);
        if (set.size() < labelList.size()) {
            String errMsg = "标签";
            for (String label : labelList) {
                if (!set.contains(label)) {
                    errMsg += label + ",";
                }
            }
            errMsg += "已更改重量，请扫码最新标签";
            return Result.fail(errMsg);
        }
        String pre = "SS-";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-");
        pre = pre + LocalDate.now().format(dtf);
        Integer maxSeq = labelMapper.selectMaxSeq(pre);
        String invoiceNumber = pre + "00001";
        if (maxSeq != null) {
            invoiceNumber = pre + String.format("%05d", maxSeq + 1);
        }
        String maxSellOrderNo = invoiceNumber;
        String idCardId = lianGuiIdCardRecord.getSellOrderId();
        if (StrUtil.isBlank(lianGuiIdCardRecord.getSellOrderId())) {
            idCardId = UUID.randomUUID().toString().replace("-", "");
            lianGuiIdCardRecord.setSellOrderId(idCardId);
            idCardRecordMapper.insertInto(lianGuiIdCardRecord, "打印");
        } else {
            idCardRecordMapper.updateBySellOrderId(lianGuiIdCardRecord);
        }
        String serialNum = labelMapper.selectMaxSerialNum();
        for (LianGuiLabelRecord lianGuiLabelRecord : lianGuiLabelRecordList) {
            lianGuiLabelRecord.setClient(lianGuiLabelRecord.getClient().split("-")[0]);
            lianGuiLabelRecord.setSellOrderId(maxSellOrderNo);
            lianGuiLabelRecord.setIdCardId(idCardId);
            lianGuiLabelRecord.setSerialNum(serialNum);
        }


        lianGuiLabelService.updateBatchById(lianGuiLabelRecordList);

        String idArr = lianGuiLabelRecordList.stream().map(LianGuiLabelRecord::getId).collect(Collectors.joining("','"));
        String url = FineReportConstant.FINE_REPORT_URI + "DQ/LianGuiXiaoHuoDetailPreview.cpt&idArr=" + idArr + "&format=pdf";
        String filePath = savePath + "preViewPdf\\";
        String fileName = maxSellOrderNo + "preViewPdf.pdf";
        CommonUtil.FRDownload(url, filePath, fileName);
        List<String> resList = new ArrayList<>();
        resList.add(httpPath + "preViewPdf/" + fileName);
        resList.add(lianGuiIdCardRecord.getSellOrderId());
        return Result.success(resList);
//        String url = "http://one.rainbowklgz.com:8093/cdq-dev-storage/lianGuiPersonInfo//preViewPdf/2504280003preViewPdf.pdf";
//        return Result.success(url);
    }

    private SSale getSSale(Integer maxKey, String invoiceNumber, Map<String, Object> clientMap, LianGuiLabelRecord lianGuiLabelRecord, LianGuiIdCardRecord lianGuiIdCardRecord) {
        Map<String, Object> userDataMap = labelMapper.selectUserData(lianGuiLabelRecord.getUpdateBy());

        SSale sSale = new SSale();
        sSale.setBillid(maxKey);
        sSale.setBillkind(1);
        sSale.setBillstate(0);
        sSale.setBillcode(invoiceNumber);
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = LocalDate.now();
        ZonedDateTime zdt = localDate.atStartOfDay(zoneId);

        Date date = Date.from(zdt.toInstant());
        sSale.setBilldate(date);
        sSale.setTraderid((Integer) clientMap.get("traderid"));
        sSale.setNotetype((Integer) clientMap.get("notetype"));
        sSale.setNoteno(lianGuiLabelRecord.getSerialNum());
        sSale.setDisc(100);
        sSale.setShopid((Integer) clientMap.get("shopid"));
        sSale.setDepartmentid((Integer) clientMap.get("departmentid"));
        sSale.setPaymethodid((Integer) clientMap.get("paymethodid"));
        sSale.setMoneyid((Integer) clientMap.get("moneyid"));
        sSale.setEmpid((Integer) clientMap.get("empid"));
        sSale.setOpid((Integer) userDataMap.get("opid"));
//        sSale.setCheckorid((Integer) clientMap.get("checkperiod"));
//        sSale.setCredid((Integer) clientMap.get("credid"));
        sSale.setTaxrate(0.0);
        sSale.setLcpayamt(0.0);
//        sSale.setAmount();
        sSale.setExrate(1);
//        sSale.setLcamount();
        sSale.setPayamt(0.0);
        sSale.setReferamt(0.0);
        sSale.setLcreferamt(0.0);
        sSale.setRefercount(0);
        sSale.setBillto((String) clientMap.get("shipto"));
        sSale.setCtraderid((Integer) clientMap.get("traderid"));
        sSale.setCloseinvoice(0);
        sSale.setUpdatetime(new Date());
        sSale.setSflag(0);
        sSale.setLinkman((String) clientMap.get("contactor"));
        sSale.setPoint(0);
        sSale.set开单状态(0);

        // 车牌
        sSale.setUserdef1(lianGuiIdCardRecord.getPlate());
        // 司机姓名
        sSale.setUserdef2(lianGuiIdCardRecord.getDriverName());
        // 手机号
        sSale.setUserdef4(lianGuiIdCardRecord.getDriverPhone());
        sSale.setRemark(lianGuiLabelRecord.getSerialNum());
        sSale.setUserdef15("扫码生成");

        return sSale;
    }

    private SSalechild getSSalechild(Integer maxKey, Double amout) {
        SSalechild sSalechild = new SSalechild();
        sSalechild.setBillid(maxKey);
        sSalechild.setItemno(1);
        sSalechild.setPayterm(0);
        sSalechild.setAmount(amout);
        sSalechild.setLcamount(amout);
        return sSalechild;
    }

    private SSaledetail getSSaledetail(Integer maxKey, Map<String, Object> mapData, Map<String, Object> warehouseMap, Map<String, Object> clientMap, Integer itemNo) {

        Map<String, Object> prodMap = labelMapper.selectProd((String) mapData.get("design_no"));
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = LocalDate.now().format(dtf);
        Double defaultPrice = ((BigDecimal) mapData.get("unit_price")).doubleValue();
        if (defaultPrice <= 0) {
            Map<String, Object> priceMap = labelMapper.selectPriceByProd((Integer) prodMap.get("unitid")
                    , format, (Integer) warehouseMap.get("storeid"), (Integer) prodMap.get("goodsid"), (Integer) clientMap.get("traderid")
                    , (Integer) clientMap.get("moneyid"), (Integer) clientMap.get("shopid"));
            defaultPrice = ((BigDecimal) priceMap.get("DefaultPrice")).doubleValue();
        }
        Integer notetype = (Integer) clientMap.get("notetype");
        double rate = 1.0;
        Integer rate100 = 0;
        if (notetype == 3) {
            rate = 1.13;
            rate100 = 13;
        }
        SSaledetail sSaledetail = new SSaledetail();
        sSaledetail.setBillid(maxKey);
        sSaledetail.setItemno(itemNo);
        sSaledetail.setStoreid((Integer) warehouseMap.get("storeid"));
        sSaledetail.setGoodsid((Integer) prodMap.get("goodsid"));
        sSaledetail.setAprice(0.0);
        sSaledetail.setPrice(defaultPrice / rate);

        BigDecimal bigDecimal = (BigDecimal) mapData.get("weight");
        double weight = bigDecimal.doubleValue();

        sSaledetail.setQuantity(weight);
        sSaledetail.setTaxrate(rate100);
        sSaledetail.setDisc(100.0);
        sSaledetail.setAmount(defaultPrice * weight);
        sSaledetail.setUnitid((Integer) prodMap.get("unitid"));
        sSaledetail.setUnitquantity(weight);
        sSaledetail.setUnitprice(defaultPrice / rate);
        sSaledetail.setUnitqty1(weight);
        sSaledetail.setUnitqty2(0.0);
        sSaledetail.setUnitqty3(0.0);
        sSaledetail.setExtqty(0.0);
        sSaledetail.setReferextqty(0.0);
        sSaledetail.setTaxamt(formatDouble((defaultPrice - defaultPrice / rate) * weight));
        sSaledetail.setGoodsamt(formatDouble(defaultPrice / rate * weight));
        sSaledetail.setLcprice(defaultPrice / rate);
        sSaledetail.setLcunitprice(defaultPrice / rate);
        sSaledetail.setLctaxprice(defaultPrice);
        sSaledetail.setLctaxamt(formatDouble((defaultPrice - defaultPrice / rate) * weight));
        sSaledetail.setLcgoodsamt(formatDouble(defaultPrice / rate * weight));
        sSaledetail.setLcamount(defaultPrice * weight);
        sSaledetail.setMargin(0.0);
        sSaledetail.setInvoiceqty(0.0);
        sSaledetail.setInvoiceamt(0.0);
        sSaledetail.setRefercount(0);
        sSaledetail.setReferbillid((Integer) mapData.get("order_billid"));
        sSaledetail.setReferbilltype(12);
        sSaledetail.setReferbillcode((String) mapData.get("order_billcode"));
        sSaledetail.setReferitemno(2);
        sSaledetail.setReferqty(0.0);
        sSaledetail.setIoqty(0.0);
        sSaledetail.setTaxprice(defaultPrice);
        sSaledetail.setOrigprice(defaultPrice / rate);
        sSaledetail.setOrigtaxprice(defaultPrice);
        sSaledetail.setIslargess(0);
        sSaledetail.setIsallot(0);
        sSaledetail.setAllotqty(0.0);
        sSaledetail.setUserdef1((String) mapData.get("quantity"));
        return sSaledetail;
    }

    public static Double formatDouble(double value) {
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        return Double.valueOf(bd.toString());
    }

    @GetMapping("/queryUsernameByAccount")
    public Result queryUsernameByNo(@RequestParam("account") String account) {
        account = account.trim();
        String username = labelMapper.selectIsHasAccount(account);
        if (StrUtil.isBlank(username)) {
            return Result.fail("没有该员工");
        }
        return Result.success(username);
    }


    @ApiOperation(value = "莲桂打印-标签打印", notes = "莲桂打印-标签打印")
    @Transactional(rollbackFor = Exception.class, transactionManager = "lianGuiTransactionManager")
    @PostMapping("/print")
    public Result print(@RequestBody LianGuiLabelRecord lianGuiLabelRecord, @RequestParam(value = "version", required = false) String version,
                        @RequestParam(value = "appid", required = false) String appid, @RequestParam(value = "type", required = false) String type,
                        @RequestParam(value = "isPc", required = false) String isPc, @RequestParam(value = "changeType", required = false) String changeType) throws UnsupportedEncodingException {
        if (!"test".equals(type)) {
            type = "";
        }

        appid = appid + type;
        if (StrUtil.isBlank(isPc)) {
            if (StrUtil.isBlank(version)) {
                return Result.fail("请更新最新版本");
            }
            String updateVersion = (String) stringRedisTemplate.opsForHash().get(appid, "version");
            if (version.compareTo(updateVersion) < 0) {
                return Result.fail("请更新最新版本");
            }
        }

        if (StrUtil.isBlank(lianGuiLabelRecord.getPrinter())) {
            return Result.fail("请选择打印机");
        }
        if (StrUtil.isBlank(lianGuiLabelRecord.getCreateBy())) {
            return Result.fail("没有该员工");
        }
        String yuanGongBianHao = labelMapper.selectYuanGongBianHao(lianGuiLabelRecord.getCreateBy());
        if (StrUtil.isBlank(yuanGongBianHao)) {
            return Result.fail("没有该员工");
        }
        lianGuiLabelRecord.setVersion(version);
        if (StrUtil.isNotBlank(lianGuiLabelRecord.getSalesOrderId())) {
            SalesOrder salesOrder = new SalesOrder();
            salesOrder.setId(lianGuiLabelRecord.getSalesOrderId());
            salesOrder.setStatus(1);
            salesOrderMapper.updateById(salesOrder);
        }
        if (StrUtil.isNotBlank(lianGuiLabelRecord.getId())) {
            if ("标签重打".equals(changeType)) {
                LianGuiLabelStatus lianGuiLabelStatus = labelStatusMapper.selectRecordByIdAndStatus(lianGuiLabelRecord.getId(), 1);
                if (lianGuiLabelStatus != null) {
                    return Result.fail("标签已销货");
                }
                lianGuiLabelRecord.setLabel(lianGuiLabelRecord.getDesignNo() + "," + lianGuiLabelRecord.getWeight().intValue() + "," + lianGuiLabelRecord.getId().substring(0, lianGuiLabelRecord.getId().length() - 4) + ',' + lianGuiLabelRecord.getId().substring(lianGuiLabelRecord.getId().length() - 4));
                labelMapper.updateById(lianGuiLabelRecord);
                String replaceDyj = URLEncoder.encode(lianGuiLabelRecord.getPrinter(), "UTF-8").replace("+", "%20");
                try {
                    //调用url，相当于浏览器携带参数直接打开网址
                    String url = FineReportConstant.FINE_REPORT_URI + "DQ/LianGuiLabel.cpt^&id=" + lianGuiLabelRecord.getId() + "^&dyj=" + replaceDyj;
                    Runtime.getRuntime().exec("cmd /c start  " + url);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return Result.success();
            }
            if ("品号更新".equals(changeType)) {
                LianGuiLabelStatus lianGuiLabelStatus = labelStatusMapper.selectRecordByIdAndStatus(lianGuiLabelRecord.getId(), 1);
                if (lianGuiLabelStatus != null) {
                    return Result.fail("标签已销货");
                }
                lianGuiLabelRecord.setLabel(lianGuiLabelRecord.getDesignNo() + "," + lianGuiLabelRecord.getWeight().intValue() + "," + lianGuiLabelRecord.getId().substring(0, lianGuiLabelRecord.getId().length() - 4) + ',' + lianGuiLabelRecord.getId().substring(lianGuiLabelRecord.getId().length() - 4));
                lianGuiLabelRecord.setCreateBy(null);
                labelMapper.updateById(lianGuiLabelRecord);
                String replaceDyj = URLEncoder.encode(lianGuiLabelRecord.getPrinter(), "UTF-8").replace("+", "%20");
                try {
                    //调用url，相当于浏览器携带参数直接打开网址
                    String url = FineReportConstant.FINE_REPORT_URI + "DQ/LianGuiLabelThree.cpt^&id=" + lianGuiLabelRecord.getId() + "^&dyj=" + replaceDyj;
                    Runtime.getRuntime().exec("cmd /c start  " + url);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return Result.success();
            }
            if ("以旧换新".equals(changeType)) {
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
                String printDate = LocalDate.now().format(dtf);

                LianGuiLabelRecord saveRecord = labelMapper.selectByLabelId(lianGuiLabelRecord.getId());

                if (saveRecord.getStatus() == 0 || saveRecord.getStatus() == 2) {
                    lianGuiLabelRecord.setLabel(lianGuiLabelRecord.getDesignNo() + "," + lianGuiLabelRecord.getWeight().intValue() + "," + lianGuiLabelRecord.getId().substring(0, lianGuiLabelRecord.getId().length() - 4) + ',' + lianGuiLabelRecord.getId().substring(lianGuiLabelRecord.getId().length() - 4));
                    labelMapper.updateById(lianGuiLabelRecord);
                    String replaceDyj = URLEncoder.encode(lianGuiLabelRecord.getPrinter(), "UTF-8").replace("+", "%20");
                    try {
                        //调用url，相当于浏览器携带参数直接打开网址
                        String url = FineReportConstant.FINE_REPORT_URI + "DQ/LianGuiLabel.cpt^&id=" + lianGuiLabelRecord.getId() + "^&dyj=" + replaceDyj;
                        Runtime.getRuntime().exec("cmd /c start  " + url);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return Result.success();
                }


                LianGuiLabelRecord breakRecord = labelMapper.selectByLabelId(lianGuiLabelRecord.getId());
                if (saveRecord.getWorkshopid() == null) {
                    return Result.fail("标签没有工作中心，请查明原因");
                }

                LianGuiLabelRecord changeRecord = new LianGuiLabelRecord();
                changeRecord.setId(lianGuiLabelRecord.getId());
                saveRecord.setCreateDate(new Date());
                saveRecord.setCreateBy(lianGuiLabelRecord.getCreateBy());


                saveRecord.setYuanGongBianHao(yuanGongBianHao);
                saveRecord.setStatus((byte) 0);
                saveRecord.setWeight(lianGuiLabelRecord.getWeight());
                saveRecord.setRation(lianGuiLabelRecord.getRation());
                String maxId = "";
                synchronized (this) {
                    maxId = labelMapper.selectSeqByPrimarkKey(printDate);
                    saveRecord.setId(null);
                    if (StrUtil.isNotBlank(maxId)) {
                        String seqPart = maxId.substring(8);
                        int seq = Integer.parseInt(seqPart);
                        if (seq >= 9999) {
                            throw new RuntimeException("当日序列号已用尽");
                        }
                        maxId = (Long.valueOf(maxId) + 1) + "";
                    } else {
                        maxId = printDate + "0001";
                    }
                    saveRecord.setId(maxId);
                    saveRecord.setLabel(lianGuiLabelRecord.getDesignNo() + "," + lianGuiLabelRecord.getWeight().intValue() + "," + maxId.substring(0, maxId.length() - 4) + ',' + maxId.substring(maxId.length() - 4));
                    labelMapper.insert(saveRecord);
                    LianGuiLabelStatus lianGuiLabelStatus = new LianGuiLabelStatus();
                    lianGuiLabelStatus.setLabelId(saveRecord.getId());
                    lianGuiLabelStatus.setStatus(saveRecord.getStatus());
                    lianGuiLabelStatus.setRecordDate(new Date());
                    lianGuiLabelStatus.setRecordBy(saveRecord.getCreateBy());
                    labelStatusMapper.insertIntoLabelStatus(lianGuiLabelStatus);

                    changeRecord.setNewLabelId(maxId);
                    changeRecord.setStatus((byte) 6);
                    labelMapper.updateById(changeRecord);
                    lianGuiLabelStatus = new LianGuiLabelStatus();
                    lianGuiLabelStatus.setLabelId(changeRecord.getId());
                    lianGuiLabelStatus.setStatus(changeRecord.getStatus());
                    lianGuiLabelStatus.setRecordDate(new Date());
                    lianGuiLabelStatus.setRecordBy(saveRecord.getCreateBy());
                    labelStatusMapper.insertIntoLabelStatus(lianGuiLabelStatus);
                }
                ZoneId zoneId = ZoneId.systemDefault();
                LocalDate localDate = LocalDate.now();
                ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
                Date date = Date.from(zdt.toInstant());
                String username = saveRecord.getCreateBy();
                Map<String, Object> userDataMap = commonMapper.selectEmployData(username);
                if (userDataMap == null) {
                    throw new RuntimeException("速达员工资料没有该员工信息");
                }
                IDraw breakRecordIDraw = materialRequisitionService.getIDraw(date, userDataMap, breakRecord.getWorkshopid());
                List<IDrawdetail> breakRecordIDrawdetail = materialRequisitionService.getIDrawdetail(breakRecord.getDesignNo(), breakRecord.getWeight());
                double amount = breakRecordIDrawdetail.stream().mapToDouble(IDrawdetail::getAmount).sum();
                breakRecordIDraw.setAmount(amount);
                synchronized (this) {
                    handleInsertIDaw(breakRecordIDraw, breakRecordIDrawdetail);
                }
                insertStatusRecord(breakRecord, username, breakRecordIDraw.getBillid(), breakRecordIDraw.getBillcode());
                IDraw iDraw = materialRequisitionService.getIDraw(date, userDataMap, saveRecord.getWorkshopid());
                iDraw.setBillkind(2);
                List<IDrawdetail> iDrawdetail = materialRequisitionService.getIDrawdetail(saveRecord.getDesignNo(), -saveRecord.getWeight());
                amount = iDrawdetail.stream().mapToDouble(IDrawdetail::getAmount).sum();
                iDraw.setAmount(amount);

                synchronized (this) {
                    handleInsertIDaw(iDraw, iDrawdetail);
                }
                insertStatusRecord(saveRecord, username, iDraw.getBillid(), iDraw.getBillcode());
                String replaceDyj = URLEncoder.encode(lianGuiLabelRecord.getPrinter(), "UTF-8").replace("+", "%20");
                String url = FineReportConstant.FINE_REPORT_URI + "DQ/LianGuiLabel.cpt^&id=" + maxId + "^&dyj=" + replaceDyj;

//                int i = 1 / 0;
                try {
//                调用url，相当于浏览器携带参数直接打开网址
                    Runtime.getRuntime().exec("cmd /c start  " + url);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return Result.success();
            }
            return Result.fail("未执行代码");
        }

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        String printDate = LocalDate.now().format(dtf);
        synchronized (this) {
//            Integer quantity = lianGuiLabelRecord.getQuantity();
//            if (quantity == null) {
            Integer quantity = 1;
//            }

            String maxId = labelMapper.selectSeqByPrimarkKey(printDate);
            for (Integer i = 0; i < quantity; i++) {

                lianGuiLabelRecord.setId(null);
                if (StrUtil.isNotBlank(maxId)) {
                    String seqPart = maxId.substring(8);
                    int seq = Integer.parseInt(seqPart);
                    if (seq >= 9999) {
                        throw new RuntimeException("当日序列号已用尽");
                    }
                    maxId = (Long.valueOf(maxId) + 1) + "";
                } else {
                    maxId = printDate + "0001";
                }
                lianGuiLabelRecord.setCreateDate(new Date());
                lianGuiLabelRecord.setId(maxId);
                lianGuiLabelRecord.setYuanGongBianHao(yuanGongBianHao);
                lianGuiLabelRecord.setStatus((byte) 0);
                lianGuiLabelRecord.setLabel(lianGuiLabelRecord.getDesignNo() + "," + lianGuiLabelRecord.getWeight().intValue() + "," + maxId.substring(0, maxId.length() - 4) + ',' + maxId.substring(maxId.length() - 4));
                labelMapper.insert(lianGuiLabelRecord);
                LianGuiLabelStatus lianGuiLabelStatus = new LianGuiLabelStatus();
                lianGuiLabelStatus.setLabelId(lianGuiLabelRecord.getId());
                lianGuiLabelStatus.setStatus(lianGuiLabelRecord.getStatus());
                lianGuiLabelStatus.setRecordDate(new Date());
                lianGuiLabelStatus.setRecordBy(lianGuiLabelRecord.getCreateBy());
                labelStatusMapper.insertIntoLabelStatus(lianGuiLabelStatus);
            }
//            int i = 1 / 0;
            String replaceDyj = URLEncoder.encode(lianGuiLabelRecord.getPrinter(), "UTF-8").replace("+", "%20");
            String url = FineReportConstant.FINE_REPORT_URI + "DQ/LianGuiLabel.cpt^&id=" + maxId + "^&dyj=" + replaceDyj;
            if (quantity > 1) {
                url = FineReportConstant.FINE_REPORT_URI + "DQ/LianGuiLabelTwo.cpt^&id=" + lianGuiLabelRecord.getSalesOrderId() + "^&dyj=" + replaceDyj;
            }
            try {
//                调用url，相当于浏览器携带参数直接打开网址
                Runtime.getRuntime().exec("cmd /c start  " + url);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return Result.success();
    }

    private void handleInsertIDaw(IDraw iDraw, List<IDrawdetail> iDrawdetailList) {
        String pre = "DR-";
        String drBillcode = commonService.getBillCode(pre, "i_draw");
        Integer drBillid = commonMapper.selectMaxBiillidByTableName("i_draw");
        iDraw.setBillid(drBillid);
        iDraw.setBillcode(drBillcode);
        for (IDrawdetail iDrawdetail : iDrawdetailList) {
            iDrawdetail.setBillid(drBillid);
        }
        iDrawMapper.insert(iDraw);
        for (IDrawdetail iDrawdetail : iDrawdetailList) {
            iDrawdetailMapper.insert(iDrawdetail);
        }
        DateTimeFormatter tempDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = LocalDate.now().format(tempDtf);
        commonMapper.execup_ab_billprint_insert(25, drBillid, drBillcode, format, iDraw.getOpid(), iDraw.getShopid());
    }

    private void insertStatusRecord(LianGuiLabelRecord origin, String username, Integer drBillid, String drBillcode) {
        LianGuiLabelRecord lianGuiLabelRecord = new LianGuiLabelRecord();
        lianGuiLabelRecord.setId(origin.getId());
        lianGuiLabelRecord.setStatus((byte) 4);
        labelMapper.updateById(lianGuiLabelRecord);
        LianGuiLabelStatus lianGuiLabelStatus = new LianGuiLabelStatus();
        lianGuiLabelStatus.setLabelId(lianGuiLabelRecord.getId());
        lianGuiLabelStatus.setStatus(lianGuiLabelRecord.getStatus());
        lianGuiLabelStatus.setRecordDate(new Date());
        lianGuiLabelStatus.setRecordBy(username);
        lianGuiLabelStatus.setBillid(drBillid);
        lianGuiLabelStatus.setBillcode(drBillcode);
        labelStatusMapper.insertIntoLabelStatus(lianGuiLabelStatus);
    }

    @GetMapping("/test")
    public Result test() {
        return Result.success("成功");
    }

}
